<?php
namespace App\Services;

use App\Models\Order;
use App\Models\OrderRefund;
use App\Models\TourOrder;
use App\Models\TourOrderRefund;
use App\Models\TourOrderRefundLog;
use App\Models\TourOrderTour;
use App\Models\LandownersOrder;
use App\Models\LandownersRefund;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 *
 * 线路订单支付服务层
 *
 * @author manong
 *
 */
class OrderPingppService extends BaseService {
    public function checkChennel($channel){
        $data = new \stdClass;
        switch ($channel) {
            case 'alipay':
                $data->payment_id = 1;
                $data->payment_name = '支付宝';
                $data->payment_code = 'alipay';
                break;

            case 'alipay_wap':
                $data->payment_id = 1;
                $data->payment_name = '支付宝';
                $data->payment_code = 'alipay';
                break;
            case 'wx':
                $data->payment_id = 2;
                $data->payment_name = '微信支付';
                $data->payment_code = 'wxPay';
                break;
            case 'wx_pub':
                $data->payment_id = 2;
                $data->payment_name = '微信支付';
                $data->payment_code = 'wxPay';
                break;
            case 'wx_wap':
                $data->payment_id = 2;
                $data->payment_name = '微信支付';
                $data->payment_code = 'wxPay';
                break;
            default:
                return $this->failure('未知支付方式');
                break;
        }

        return $this->success($data);
    }


    public function getPayPara($user_id,$order_id,$seller_name,$order_sn,$order_amount,$channel,$needs_full=0)
    {
        $resultData = $this->createCharge($user_id,$order_id,$seller_name,$order_sn,$order_amount,$channel);
        if(!$resultData['result']){
            return $this->failure($resultData['msg']);
        }

        $result = $resultData['data'];

        if($needs_full){
            return $this->success($result);
        }else{
            switch ($channel) {
                case 'wx':
                    $sign = $result->credential->$channel;
                    break;
                default:
                    $sign = $result->credential->$channel->orderInfo;
                    break;
            }

            return $this->success($sign);// 输出 Ping++ 返回的支付凭据 Charge
        }

    }

    private function createCharge($user_id,$order_id,$seller_name,$order_sn,$order_amount,$channel){
        //##验证##
        //alipay,alipay_wap,alipay_pc_direct,alipay_qr
        //wx,wx_wap,wx_pub_qr
        //请查看文档 https://pingxx.com/document/api#api-c-new；

        //$openid = Input::get('openid'); //wx_pub的场合，必须
        $userinfo =User::find($user_id);
        if(!$userinfo){
            return $this->failure('用户不存在');
        }
//        if($channel=='wx_pub'){
//            if(!$openid){
//                return $this->args_invalid();
//            }
//        }

        require base_path('vendor/pingplusplus/pingpp-php/init.php');

        $order_type ='goods';
        if(starts_with($order_sn,'T')){
            $order_type ="tour";
        } else if(starts_with($order_sn,'L')){
            $order_type ="landowner";
        }
        // api_key 获取方式：登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->开发信息-> Secret Key
        //$api_key = config('maqu.APP_DEBUG')?config('maqu.PINGPP_API_TEST_KEY'):config('maqu.PINGPP_API_LIVE_KEY');
        $api_key = config('maqu.PINGPP_API_LIVE_KEY');
        // app_id 获取方式：登录 [Dashboard](https://dashboard.pingxx.com)->点击你创建的应用->应用首页->应用 ID(App ID)
        $app_id = config('maqu.PINGPP_APP_ID');

        $amount =$order_amount*100;
        $orderNo = $order_sn;
        $charge = DB::table('pingxx_charge_log')
            ->where('status',0)
            ->where('order_id',$order_id)
            ->where('order_sn',$orderNo)
            ->where('amount',$amount)
            ->value('response_json');
        if($charge){
            $ch = json_decode($charge,true) ;
        }else{

            /**
             * 设置请求签名密钥，密钥对需要你自己用 openssl 工具生成，如何生成可以参考帮助中心：https://help.pingxx.com/article/123161；
             * 生成密钥后，需要在代码中设置请求签名的私钥(rsa_private_key.pem)；
             * 然后登录 [Dashboard](https://dashboard.pingxx.com)->点击右上角公司名称->开发信息->商户公钥（用于商户身份验证）
             * 将你的公钥复制粘贴进去并且保存->先启用 Test 模式进行测试->测试通过后启用 Live 模式
             */

            // 设置私钥内容方式1
            \Pingpp\Pingpp::setPrivateKeyPath(base_path('/keys/pingpp_rsa_private_key.pem'));

            /**
             * $extra 在使用某些渠道的时候，需要填入相应的参数，其它渠道则是 array()。
             * 以下 channel 仅为部分示例，未列出的 channel 请查看文档 https://pingxx.com/document/api#api-c-new；
             * 或直接查看开发者中心：https://www.pingxx.com/docs/server/charge；包含了所有渠道的 extra 参数的示例；
             */

            $extra = array();
            switch ($channel) {
                case 'alipay':
                    break;
                case 'alipay_wap':
                    $extra = array(
                        // success_url 和 cancel_url 在本地测试不要写 localhost ，请写 127.0.0.1。URL 后面不要加自定义参数
                        'success_url' => config('maqu.WAP_URL').'/html/h5PaySuccess.html'
                    );
                    break;
                case 'wx':
                    break;
                case 'wx_pub':
                    $extra = array(
                        'open_id' => $userinfo->wx_openid// 用户在商户微信公众号下的唯一标识，获取方式可参考 pingpp-php/lib/WxpubOAuth.php
                    );
                    break;
                case 'wx_wap':
                    break;
                default:
                    return $this->failure('该支付方式未实现');
                    break;
            }
            \Pingpp\Pingpp::setApiKey($api_key);// 设置 API Key

            $ch = \Pingpp\Charge::create(
                array(

                    //请求参数字段规则，请参考 API 文档：https://www.pingxx.com/api#api-c-new
                    'subject'   => $seller_name .' 订单号：' . $order_sn,
                    'body'      => $seller_name .' 订单号：' . $order_sn,
                    'amount'    => $amount,//订单总金额, 人民币单位：分（如订单总金额为 1 元，此处请填 100）
                    'order_no'  => $orderNo,// 推荐使用 8-20 位，要求数字或字母，不允许其他字符
                    'currency'  => 'cny',
                    'extra'     => $extra,
                    'channel'   => $channel,// 支付使用的第三方支付渠道取值，请参考：https://www.pingxx.com/api#api-c-new
                    'client_ip' => $_SERVER['REMOTE_ADDR'],// 发起支付请求客户端的 IP 地址，格式为 IPV4，如: 127.0.0.1
                    'app'       => array('id' => $app_id)
                )
            );
            $charge_info = json_decode($ch,true);
             // Log::ERROR($ch);    
            /* 交易记录 */
            $pingxx_charge = array(
                'create_at'  => gmtime(),//创建时间
                'appid'  => $charge_info['app'], //商户id
                'charge_id' => $charge_info['id'],//交易号
                'status' => 0 ,//状态
                'response_json' => $ch,//交易内容
                'order_type'=>$order_type,//订单类型
                'order_id'  => $order_id,//订单id
                'order_sn'  =>$orderNo,//订单编号
                'amount'  => $amount,//订单金额
            );

            DB::table('pingxx_charge_log')->insert($pingxx_charge);

        }
        return $this->success($ch);
    }
    public function createRefound($user_id,$order_id,$seller_name,$order_sn,$order_amount,$channel){

        $userinfo =User::find($user_id);
        if(!$userinfo){
            return $this->failure('用户不存在');
        }
        //获取用户订单支付charge_id
        $charge_id = DB::table('pingxx_charge_log')
                ->where('order_id',$order_id)
                ->where('order_sn',$order_sn)
                ->where('status',1)
                ->first();
        if(!$charge_id){
            return $this->failure('该订单不支持退款');
        }

        require base_path('vendor/pingplusplus/pingpp-php/init.php');
        $order_type ='goods';
        if(starts_with($order_sn,'T')){
            $order_type ="tour";
        } else if(starts_with($order_sn,'L')){
            $order_type ="landowner";
        }
        // api_key 获取方式：登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->开发信息-> Secret Key
        //$api_key = config('maqu.APP_DEBUG')?config('maqu.PINGPP_API_TEST_KEY'):config('maqu.PINGPP_API_LIVE_KEY');
        $api_key = config('maqu.PINGPP_API_LIVE_KEY');
        // app_id 获取方式：登录 [Dashboard](https://dashboard.pingxx.com)->点击你创建的应用->应用首页->应用 ID(App ID)
        $app_id = config('maqu.PINGPP_APP_ID');

        $amount =$order_amount*100;
        $orderNo = $order_sn;
        $refound = DB::table('pingxx_refund_log')
            ->where('status',0)
            ->where('order_id',$order_id)
            ->where('order_sn',$orderNo)
            ->where('amount',$amount)
            ->value('response_json');
        if($refound){
            $re = $refound;
        }else{

            /**
             * 设置请求签名密钥，密钥对需要你自己用 openssl 工具生成，如何生成可以参考帮助中心：https://help.pingxx.com/article/123161；
             * 生成密钥后，需要在代码中设置请求签名的私钥(rsa_private_key.pem)；
             * 然后登录 [Dashboard](https://dashboard.pingxx.com)->点击右上角公司名称->开发信息->商户公钥（用于商户身份验证）
             * 将你的公钥复制粘贴进去并且保存->先启用 Test 模式进行测试->测试通过后启用 Live 模式
             */

            // 设置私钥内容方式1
            \Pingpp\Pingpp::setPrivateKeyPath(base_path('/keys/pingpp_rsa_private_key.pem'));

            /**
             * $extra 在使用某些渠道的时候，需要填入相应的参数，其它渠道则是 array()。
             * 以下 channel 仅为部分示例，未列出的 channel 请查看文档 https://pingxx.com/document/api#api-c-new；
             * 或直接查看开发者中心：https://www.pingxx.com/docs/server/charge；包含了所有渠道的 extra 参数的示例；
             */

//            $extra = array();
//            switch ($channel) {
//                case 'alipay':
//                    break;
//                case 'alipay_wap':
//                    $extra = array(
//                        // success_url 和 cancel_url 在本地测试不要写 localhost ，请写 127.0.0.1。URL 后面不要加自定义参数
//                        'success_url' => config('maqu.WAP_URL').'/html/h5PaySuccess.html'
//                    );
//                    break;
//                case 'wx':
//                    break;
//                case 'wx_pub':
//                    $extra = array(
//                        'open_id' => $userinfo->wx_openid// 用户在商户微信公众号下的唯一标识，获取方式可参考 pingpp-php/lib/WxpubOAuth.php
//                    );
//                    break;
//                case 'wx_wap':
//                    break;
//                default:
//                    return $this->failure('该支付方式未实现');
//                    break;
//            }
            \Pingpp\Pingpp::setApiKey($api_key);// 设置 API Key

            $ch = \Pingpp\Charge::retrieve($charge_id->charge_id);//ch_id 是已付款的订单号
            $re = $ch->refunds->create(
                array(
                    'amount' => $amount,
                    'description' => '用户退款'
                )
            );
            $refund_info = json_decode($re,true);
            /* 交易记录 */
            $pingxx_refunds = array(
                'create_at'  => gmtime(),//创建时间
                'appid'  => $charge_id->appid, //商户id
                'refund_id' => $refund_info['id'],//退款号
                'charge_id' => $charge_id->charge_id,//交易支付号
                'status' => 0 ,//状态
                'response_json' => $re,//交易内容
                'order_type'=>$order_type,//订单类型
                'order_id'  => $order_id,//订单id
                'order_sn'  =>$orderNo,//订单编号
                'amount'  => $amount,//订单金额
            );

            DB::table('pingxx_refund_log')->insert($pingxx_refunds);

        }
        return $this->success($re);
    }

    /**
     * 创建批量退款对象：
     * @param $order_ids 订单id
     * @return json
     */
    public function createBatchRefound($order_ids){
        if(!$order_ids){
            return $this->failure('退款对象不存在');
        }
        $charges = DB::table('pingxx_charge_log')
            ->where('status',1)
            ->whereIn('order_id',$order_ids)
            ->lists('charge_id');
        if($charges == ''){
            return $this->failure('该订单不支持退款');
        }
        $app_id = config('maqu.PINGPP_APP_ID');
        $api_key = config('maqu.PINGPP_API_LIVE_KEY');
        require base_path('vendor/pingplusplus/pingpp-php/init.php');
        DB::beginTransaction();
        \Pingpp\Pingpp::setApiKey($api_key);
        \Pingpp\Pingpp::setPrivateKeyPath(base_path('/keys/pingpp_rsa_private_key.pem'));
        try {
            $batch_re = \Pingpp\BatchRefund::create(
                [
                    'app'         => $app_id,
                    'batch_no'    => uniqid('tuankuana'),         //批量退款批次号，3-24位，允许字母和英文
                    'description' => '组团失败批量退款',    //批量退款详情，最多 255 个 Unicode 字符
                    'charges'     => $charges,
                ]
            );
            echo $batch_re;
            DB::commit();
        } catch (\Pingpp\Error\Base $e) {
            if ($e->getHttpStatus() != null) {
                header('Status: ' . $e->getHttpStatus());
                echo $e->getHttpBody();
            } else {
                echo $e->getMessage();
            }
        }
    }

    /**
     * 验证 webhooks 签名方法：
     * raw_data：Ping++ 请求 body 的原始数据即 event ，不能格式化；
     * signature：Ping++ 请求 header 中的 x-pingplusplus-signature 对应的 value 值；
     * pub_key_path：读取你保存的 Ping++ 公钥的路径；
     * pub_key_contents：Ping++ 公钥，获取路径：登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->开发信息-> Ping++ 公钥
     */
    public function verify_signature($raw_data, $signature, $pub_key_path) {
        $pub_key_contents = file_get_contents($pub_key_path);
        // php 5.4.8 以上，第四个参数可用常量 OPENSSL_ALGO_SHA256
        return openssl_verify($raw_data, base64_decode($signature), $pub_key_contents, 'sha256');
    }

    public function updateOrderWhenSucceeded($charge)
    {

        //商户订单号
        $out_trade_no = $charge['order_no'];
        //交易号
        $trade_no = $charge['transaction_no'];
      //  用户支付凭证id  由Ping++生成
        $charge_id = $charge['id'];
        //商户id
        $appid = $charge['app'];

        //根据订单号首字符判断是商品订单(G)还是旅游订单(T)
        $snFisrt = substr($out_trade_no,0,1);
        switch($snFisrt){
            case 'G':   //商品
                $orderInfo = Order::where('order_sn',$out_trade_no)->first();
                if(!$orderInfo){
                    Log::ERROR('未找到该订单order_sn:'.$out_trade_no);
                    return false;
                }

                Log::info('order_amount:',['order_amount'=>$orderInfo->order_amount]);

                if (intval($orderInfo->order_amount*100) != $charge['amount'])
                {

                    /* 支付的金额与实际金额不一致 */
                    Log::ERROR('支付的金额与实际金额不一致order_amount:'.$orderInfo->order_amount."/charge_amount:".$charge['amount']);
                    return false;
                }

                if($orderInfo->status == ORDER_ACCEPTED) {
                    Log::ERROR('该订单支付已成功，请勿重复操作order_sn:' . $out_trade_no);
                    return true;
                }else if($orderInfo->status == ORDER_CANCELED){
                    //已取消订单允许支付（用户对应前台支付与自动取消处理同时的场合） 20170423 manong
                }elseif($orderInfo->status != ORDER_PENDING){
                    Log::ERROR('订单已不可支付order_sn:'.$out_trade_no);
                    return false;
                }

                DB::beginTransaction();
                try{
                    //更新Ping++支付凭证
                    DB::table('pingxx_charge_log')
                        ->where('order_id',$orderInfo->order_id)
                        ->where('charge_id',$charge_id)
                        ->where('appid',$appid)
                        ->where('order_sn',$orderInfo->order_sn)
                        ->where('amount',$orderInfo->order_amount*100)
                        ->update(['status' => 1]);

                    //更新旅行订单数据
                    $orderInfo->out_trade_sn = $trade_no;
                    $orderInfo->pay_time = gmtime();
                    $orderInfo->status = TOUR_ORDER_ACCEPTED;

                    $orderInfo->save();

                    $orderService = new OrderService();
                    switch($orderInfo->extension){
                        case TOUR_ORDER_EXTENSION_NORMAL:
                            /* 支付成功 减去商品库存 */
                            $orderService->changeStock('-',$orderInfo->order_id,false);
                            break;
                        default:;
                    }

                    //添加订单日志
                    $old_status = $orderService->OrderStatus(ORDER_PENDING);
                    $new_status = $orderService->OrderStatus(ORDER_ACCEPTED);
                    $orderService->addOrderLog($orderInfo->order_id,$orderInfo->buyer_name,$old_status,$new_status,'用户支付',false);
                    DB::commit();
                }catch (\Exception $e){
                    Log::ERROR($e->getMessage());
                    DB::rollback();
                    return false;
                }

                break;
            case 'T': //线路
                $tourOrder = TourOrder::where('order_sn',$out_trade_no)->with('tourOrderTour')->first();
                if(!$tourOrder){
                    Log::ERROR('未找到该路线订单order_sn:'.$out_trade_no);
                    return false;
                }

                Log::info('order_amount:',['order_amount'=>$tourOrder->order_amount]);

                if (intval($tourOrder->order_amount*100) != $charge['amount'])
                {
                    /* 支付的金额与实际金额不一致 */
                    Log::ERROR('支付的金额与实际金额不一致order_amount:'.$tourOrder->order_amount."/charge_amount:".$charge['amount']);
                    return false;
                }

                if($tourOrder->status == TOUR_ORDER_ACCEPTED || $tourOrder->status == TOUR_ORDER_SUBMITTED){
                    Log::ERROR('该订单支付已成功，请勿重复操作order_sn:'.$out_trade_no);
                    return true;
                }else if($tourOrder->status == TOUR_ORDER_CANCELED){
                    //已取消订单允许支付（用户对应前台支付与自动取消处理同时的场合） 20170423 manong
                }elseif($tourOrder->status != TOUR_ORDER_PENDING){
                    Log::ERROR('订单已不可支付order_sn:'.$out_trade_no);
                    return false;
                }

                DB::beginTransaction();
                try{

                    //更新Ping++支付凭证
                    DB::table('pingxx_charge_log')
                        ->where('order_id',$tourOrder->order_id)
                        ->where('charge_id',$charge_id)
                        ->where('appid',$appid)
                        ->where('order_sn',$tourOrder->order_sn)
                        ->where('amount',$tourOrder->order_amount*100)
                        ->update(['status' => 1]);
                   //判断是单买还是团购
                    $tourOrderService = new TourOrderService();
                    switch($tourOrder->extension){
                        case TOUR_ORDER_EXTENSION_NORMAL:
                            //更新旅行订单数据
                            $tourOrder->out_trade_sn = $trade_no;
                            $tourOrder->pay_time = gmtime();
                            $tourOrder->status = TOUR_ORDER_ACCEPTED ;//已付款待出行
                            $tourOrder->save();
                            /* 支付成功 减去商品库存 */
                            //changeStock($type='-',$extension, $order_id,$schedule_id,$quantity,$pintuan_id = 0,$withTrans = false)
                            $quantity = $tourOrder->tourOrderTour->quantity;//只允许小孩,则计算小孩数量
                            $tourOrderService->changeStock('-',$tourOrder->tourOrderTour->schedule_id,$quantity,$tourOrder->tuan_id,false);
                            break;
                        case TOUR_ORDER_EXTENSION_GROUPBUY:
                            //更新旅行订单数据
                            $tourOrder->out_trade_sn = $trade_no;
                            $tourOrder->pay_time = gmtime();
                            $tourOrder->status = TOUR_ORDER_SUBMITTED;//已付款等待成团
                            $tourOrder->save();
                            //更新团状态
                            $tourOrderService->updateTuanState($tourOrder->order_id,$tourOrder->tuan_id,false);

                            $tuanQuantityData = $tourOrderService->getTuanQuantity($tourOrder->tuan_id);
                            if(!$tuanQuantityData['result']){
                                DB::rollback();
                                return false;
                            }
                            $quantity = $tuanQuantityData['data'];
                            $tourOrderService->changeStock('-',$tourOrder->tourOrderTour->schedule_id,$quantity,$tourOrder->tuan_id,false);

                        break;
                    }

                    //添加订单日志
                    $old_status = $tourOrderService->tourOrderStatus(TOUR_ORDER_PENDING);
                    $new_status =$tourOrderService->tourOrderStatus(TOUR_ORDER_ACCEPTED);
                    $tourOrderService->addTourOrderLog($tourOrder->order_id,$tourOrder->buyer_name,$old_status,$new_status,'用户支付',false);
                    DB::commit();
                }catch (\Exception $e){
                    Log::ERROR($e->getMessage());
                    DB::rollback();
                    return false;
                }

                break;
            case 'L': //做地主
                $landownersOrder = LandownersOrder::where('order_sn',$out_trade_no)->first();
                if(!$landownersOrder){
                    Log::ERROR('未找到该订单order_sn:'.$out_trade_no);
                    return false;
                }

                Log::info('order_amount:',['order_amount'=>$landownersOrder->order_amount]);

                if (intval($landownersOrder->order_amount*100) != $charge['amount'])
                {

                    /* 支付的金额与实际金额不一致 */
                    Log::ERROR('支付的金额与实际金额不一致order_amount:'.$landownersOrder->order_amount."/charge_amount:".$charge['amount']);
                    return false;
                }

                if($landownersOrder->status == LANDOWNERS_ORDER_ACCEPTED) {
                    Log::ERROR('该订单支付已成功，请勿重复操作order_sn:' . $out_trade_no);
                    return true;
                }else if($landownersOrder->status == LANDOWNERS_ORDRE_CANCELED){
                    //已取消订单允许支付（用户对应前台支付与自动取消处理同时的场合） 20170423 manong
                }elseif($landownersOrder->status != LANDOWNERS_ORDER_PENDING){
                    Log::ERROR('订单已不可支付order_sn:'.$out_trade_no);
                    return false;
                }

                DB::beginTransaction();
                try{
                    //更新Ping++支付凭证
                    DB::table('pingxx_charge_log')
                        ->where('order_id',$landownersOrder->order_id)
                        ->where('charge_id',$charge_id)
                        ->where('appid',$appid)
                        ->where('order_sn',$landownersOrder->order_sn)
                        ->where('amount',$landownersOrder->order_amount*100)
                        ->update(['status' => 1]);

                    //更新做地主订单数据
                    $landownersOrder->out_trade_sn = $trade_no;
                    $landownersOrder->pay_time = gmtime();
                    $landownersOrder->status = LANDOWNERS_ORDER_ACCEPTED;

                    $landownersOrder->save();

                    $orderService = new LandownersOrderService();
                    /* 支付成功 减去商品库存 */
                    $orderService->changeStock('-',$landownersOrder->order_id,false);
                    //添加订单日志
                    $old_status = $orderService->OrderStatus(LANDOWNERS_ORDER_PENDING);
                    $new_status = $orderService->OrderStatus(LANDOWNERS_ORDER_ACCEPTED);
                    //添加订单日志
                    $orderService->addLandownersOrderLog($landownersOrder->order_id,$landownersOrder->buyer_name,$old_status,$new_status,'用户支付','',false);
                    DB::commit();
                }catch (\Exception $e){
                    Log::ERROR($e->getMessage());
                    DB::rollback();
                    return false;
                }
            default:

                break;
        }

        return true;

    }

    public function updateOrderWhenRefundSucceeded($refund)
    {
//        Log::ERROR(json_encode($refund));
        foreach ($refund as $k => $item) {
            Log::info('$refund', [$k . ':' => $item]);

            //商户订单号
            $out_trade_no = $item['charge_order_no'];
            Log::ERROR('未找到该退款单order_sn:' . $item['charge_order_no']);
            $trade_no = $item['transaction_no'];

            //根据订单号首字符判断是商品订单(G)还是旅游订单(T)
            $snFisrt = substr($out_trade_no, 0, 1);
            switch ($snFisrt) {
                case 'G':   //商品
                    $orderInfo = Order::where('order_sn', $out_trade_no)->first();//商品订单信息

                    if (!$orderInfo) {
                        Log::ERROR('未找到该订单order_sn:' . $out_trade_no);
                        return false;
                    }

                    $refund_order = OrderRefund::where('order_id', $orderInfo->order_id)->first();//退款订单信息

                    if (!$refund_order) {
                        Log::ERROR('未找到该退款单order_sn:' . $out_trade_no);
                        return false;
                    }

                    Log::info('order_amount:', ['order_amount' => $orderInfo->order_amount]);

//                if (intval($orderInfo->order_amount*100) != $refund['amount'])
//                {
//
//                    /* 退款的金额与实际金额不一致 */
//                    Log::ERROR('退款的金额与实际金额不一致order_amount:'.$orderInfo->order_amount."/charge_amount:".$refund['amount']);
//                    return false;
//                }

                    if ($orderInfo->status == ORDER_REFUND) {
                        Log::ERROR('该订单已退款，请勿重复操作order_sn:' . $out_trade_no);
                        return false;
                    } elseif ($orderInfo->status != TOUR_ORDER_AGREE) {
                        Log::ERROR('此订单不可退款order_sn:' . $out_trade_no);
                        return false;
                    } elseif ($refund_order->refund_status != TOUR_REFUND_REFUNDING) {
                        Log::ERROR('此订单不可退款order_sn:' . $out_trade_no);
                        return false;
                    }
                    DB::beginTransaction();
                    try {

                        //更新商品订单状态
                        $orderInfo->refund_tradesn = $trade_no;
                        $orderInfo->status = TOUR_REFUND_FINISHED; //退款成功

                        $orderInfo->save();

                        $orderService = new OrderService();
                        switch ($orderInfo->extension) {
                            case TOUR_ORDER_EXTENSION_NORMAL:
                                //获取商品id
                                $goods_id = DB::table('order_goods')->where('order_id', $orderInfo->order_id)->value('goods_id');
                                /* 退款成功 加回商品库存 */
                                $orderService->addStock($orderInfo->extension, $orderInfo->order_id, $goods_id);
                                break;
                            default:
                                ;
                        }

                        //添加订单日志
                        $orderService->addOrderLog($orderInfo->order_id, $orderInfo->buyer_name, TOUR_ORDER_AGREE, TOUR_REFUND_FINISHED, '用户退款', false);

                        //更新退款单状态
                        $refund_order->refund_status = TOUR_REFUND_FINISHED; //退款成功

                        $refund_order->save();
                        //添加退款单日志
                        $refundservice = new RefundService();

                        $refundservice->addOrderRefundLog($refund_order->refund_id, 1, $orderInfo->buyer_name, TOUR_ORDER_AGREE, TOUR_REFUND_FINISHED, '用户退款');

                        DB::commit();

                    } catch (\Exception $e) {
                        Log::ERROR($e->getMessage());
                        DB::rollback();
                        return false;
                    }

                    break;
                case 'L':   //商品
                    $orderInfo = LandownersOrder::where('order_sn', $out_trade_no)->first();//商品订单信息

                    if (!$orderInfo) {
                        Log::ERROR('未找到该订单order_sn:' . $out_trade_no);
                        return false;
                    }

                    $refund_order = LandownersRefund::where('order_id', $orderInfo->order_id)->first();//退款订单信息

                    if (!$refund_order) {
                        Log::ERROR('未找到该退款单order_sn:' . $out_trade_no);
                        return false;
                    }

                    Log::info('order_amount:', ['order_amount' => $orderInfo->order_amount]);

//                if (intval($orderInfo->order_amount*100) != $refund['amount'])
//                {
//
//                    /* 退款的金额与实际金额不一致 */
//                    Log::ERROR('退款的金额与实际金额不一致order_amount:'.$orderInfo->order_amount."/charge_amount:".$refund['amount']);
//                    return false;
//                }

                    if ($orderInfo->status == LANDOWNERS_ORDRE_REFUND) {
                        Log::ERROR('该订单已退款，请勿重复操作order_sn:' . $out_trade_no);
                        return false;
                    } elseif ($orderInfo->status != LANDOWNERS_REFUND_AGREE) {
                        Log::ERROR('此订单不可退款order_sn:' . $out_trade_no);
                        return false;
                    } elseif ($refund_order->refund_status != LANDOWNERS_REFUND_REFUNDING) {
                        Log::ERROR('此订单不可退款order_sn:' . $out_trade_no);
                        return false;
                    }
                    DB::beginTransaction();
                    try {

                        //更新商品订单状态
                        $orderInfo->refund_tradesn = $trade_no;
                        $orderInfo->status = LANDOWNERS_ORDRE_REFUND; //退款成功

                        $orderInfo->save();

                        $orderService = new LandownersOrderService();
                        switch ($orderInfo->extension) {
                            case TOUR_ORDER_EXTENSION_NORMAL:
                                //获取商品id
                                $goods_id = DB::table('landowners_order_evaluation')->where('order_id', $orderInfo->order_id)->value('landowners_id');
                                /* 退款成功 加回商品库存 */
                                $orderService->addStock($orderInfo->extension, $orderInfo->order_id, $goods_id);
                                break;
                            default:
                                ;
                        }

                        //添加订单日志
                        $orderService->addLandownersOrderLog($orderInfo->order_id, $orderInfo->buyer_name, LANDOWNERS_REFUND_AGREE, LANDOWNERS_ORDRE_REFUND, '用户退款', false);

                        //更新退款单状态
                        $refund_order->refund_status = LANDOWNERS_ORDRE_REFUND; //退款成功

                        $refund_order->save();
                        //添加退款单日志
                        $refundservice = new LandownersRefundService();

                        $refundservice->addOrderRefundLog($refund_order->refund_id, 1, $orderInfo->buyer_name, LANDOWNERS_REFUND_AGREE, LANDOWNERS_ORDRE_REFUND, '用户退款');

                        DB::commit();

                    } catch (\Exception $e) {
                        Log::ERROR($e->getMessage());
                        DB::rollback();
                        return false;
                    }

                    break;
                case 'T': //线路

                    $tourOrder = TourOrder::where('order_sn', $out_trade_no)->with('tourOrderTour')->first();

                    if (!$tourOrder) {
                        Log::ERROR('未找到该路线订单order_sn:' . $out_trade_no);
                        return false;
                    }
                    $tourOrderrefund = TourOrderRefund::where('order_id', $tourOrder->order_id)->first();

                    if (!$tourOrderrefund) {
                        Log::ERROR('未找到该路线退款订单order_sn:' . $out_trade_no);
                        return false;
                    }
                    Log::info('order_amount:', ['order_amount' => $tourOrder->order_amount]);

//                if (intval($tourOrder->order_amount*100) != $charge['amount'])
//                {
//                    /* 支付的金额与实际金额不一致 */
//                    Log::ERROR('支付的金额与实际金额不一致order_amount:'.$tourOrder->order_amount."/charge_amount:".$charge['amount']);
//                    return false;
//                }

                    if ($tourOrder->status == ORDER_REFUND) {
                        Log::ERROR('该订单已退款，请勿重复操作order_sn:' . $out_trade_no);
                        return false;
                    } elseif ($tourOrder->status != TOUR_ORDER_AGREE) {
                        Log::ERROR('此订单不可退款order_sn:' . $out_trade_no);
                        return false;
                    } elseif ($tourOrderrefund->refund_status != TOUR_REFUND_REFUNDING) {
                        Log::ERROR('此订单不可退款order_sn:' . $out_trade_no);
                        return false;
                    }

                    DB::beginTransaction();
                    try {

                        //更新线路订单状态
                        $tourOrder->refund_out_tradesn = $trade_no;
                        $tourOrder->status = TOUR_REFUND_FINISHED;

                        $tourOrder->save();

                        //更新退款单状态
                        $tourOrderrefund->refund_status = TOUR_REFUND_FINISHED; //退款成功
                        $tourOrderrefund->last_time = gmtime();

                        $tourOrderrefund->save();

                        $tourOrderService = new TourOrderService();
                        $tourrefundservice = new TourRefundService();
                        $tourtuanservice = new TourTuanService();

                        //添加线路订单日志
                        $tourOrderService->addTourOrderLog($tourOrder->order_id, $tourOrder->buyer_name, TOUR_ORDER_AGREE, TOUR_REFUND_FINISHED, '线路退款', false);

                        //添加退款单日志
                        $tourrefundservice->addOrderRefundLog($tourOrderrefund->refund_id, $tourOrder->buyer_name, TOUR_ORDER_AGREE, TOUR_REFUND_FINISHED, '线路退款', false);

                        switch ($tourOrder->extension) {
                            case TOUR_ORDER_EXTENSION_NORMAL:
                                /* 退款成功 加回线路当日行程库存 */
                                $quantity = $tourOrder->tourOrderTour->quantity;
                                $tourOrderService->changeStock('+', $tourOrder->tourOrderTour->schedule_id, $quantity, false);
                                break;
                            case TOUR_ORDER_EXTENSION_GROUPBUY:

                                $tuanQuantityData = $tourOrderService->getTuanQuantity($tourOrder->tuan_id);
                                $tourtuan_state = DB::table('tour_tuan')->where('tuan_id', $tourOrder->tuan_id)->value('state');

                                if (!$tuanQuantityData['result']) {
                                    DB::rollback();
                                    return false;
                                }
                                $quantity = $tuanQuantityData['data'];

                                if ($tourtuan_state == TUAN_STATE_SUCCESS) {

                                    $tourOrderService->changeStock('+', $tourOrder->tourOrderTour->schedule_id, $quantity, false);//增加行程库存

                                } elseif ($tourtuan_state == TUAN_STATE_WAITE) {

                                    $tourOrderService->changeStock('+', $tourOrder->tourOrderTour->schedule_id, $quantity, false);//增加行程库存
                                    $tourtuanservice->changeTuanStock('+', $tourOrder->tuan_id, $quantity, false);//增加团库存
                                } else {
                                    return false;
                                }
                                break;
                            default:
                                ;
                        }
                        DB::commit();
                    } catch (\Exception $e) {
                        Log::ERROR($e->getMessage());
                        DB::rollback();
                        return false;
                    }

                    break;
                default:

                    break;
            }

            return true;
        }
    }

}
